package ian.android.lovewords.words;

import ian.android.lovewords.time.TimeManip;
import ian.android.lovewords.time.TimeStruct;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class WordList {
	
	public int ListNum;
	
	public TimeStruct LastShowTime;
	
	public int Level;
	
	ArrayList<WordBlock> WordArrayList;
	
	public WordList( int ListNum)
	{
		this.ListNum = ListNum;
		WordArrayList = null;
	}
	
	public int getWordsNumInList()
	{
		if (WordArrayList == null)
			return -1;
		return WordArrayList.size();
	}
	
	public void LoadListStream( InputStream in )
	{
		WordArrayList = new ArrayList<WordBlock>();
		String tempString;
		try {
			BufferedReader br = new BufferedReader( new InputStreamReader(in, "UNICODE"));
			 while ((tempString = br.readLine()) != null) 
			 {
				 StringTokenizer st = new StringTokenizer( tempString);
				 WordBlock newword = new WordBlock(ListNum);
				 newword.Word = st.nextToken();
				 newword.Meaning = st.nextToken();
				 WordArrayList.add(newword);
			 }
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public WordBlock getNextWordRecite()
	{
		for( WordBlock tmp :this.WordArrayList )
		{
			if( tmp.StudyLevel == 1 )
			{
				if( TimeManip.LessThanMin(tmp.LastSeenTime, TimeManip.GetTimeStructNow(), 5) )
				{
					UpdateBundleWords(tmp);
					AddLevel_RefreshTime(tmp);
					return tmp;
				}
			}
			else if( tmp.StudyLevel == 2 )
			{
				if( TimeManip.LessThanMin(tmp.LastSeenTime, TimeManip.GetTimeStructNow(), 30) )
				{
					UpdateBundleWords(tmp);
					AddLevel_RefreshTime(tmp);
					return tmp;
				}
			}
			else if( tmp.StudyLevel == 0 )
			{
				if( tmp == WordArrayList.get( WordArrayList.size() - 1 ) )
				{
					UpdateWordsLeft();
				}
				AddLevel_RefreshTime(tmp);
				return tmp;
			}
			else continue;
		}
		return null;
	}
	
	private void AddLevel_RefreshTime( WordBlock w )
	{
		w.StudyLevel++;
		w.LastSeenTime = TimeManip.GetTimeStructNow();
	}
	
	private void UpdateWordsLeft()
	{
		for( WordBlock tmp : this.WordArrayList )
		{
			if(tmp.StudyLevel >= 3)
				continue;
			if(tmp.StudyLevel == 2)
				tmp.LastSeenTime.Min -= 30;
			if(tmp.StudyLevel == 1)
				tmp.LastSeenTime.Min -= 5;
		}
	}
	
	private void UpdateBundleWords( WordBlock w )
	{
		for(WordBlock tmp:this.WordArrayList)
		{
			if(tmp.StudyLevel == w.StudyLevel)
			{
				tmp.LastSeenTime = w.LastSeenTime;
			}
			if(tmp.StudyLevel < w.StudyLevel)
			{
				break;
			}
		}
	}
}
